<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>签名</title>
</head>
<style>
    .reset_btn {
        margin-right: 30px;
        background-color: #f56c6c
    }
    
    .save_btn {
        margin-right: 30px;
        color: #fff;
        background-color: #67c23a;
    }
    
    .canvas {
        background-color: aquamarine;
    }
    
    .container {
        width: 800px;
        height: 600px;
    }
</style>


<body>
    <div class="container">
        <canvas id="canvas" width="600px" height="400px"></canvas>
        <div class="operate">
            <div class="save_btn" onclick="handleSave()">保存</div>
            <div class="reset_btn" onclick="handleReset()">重置</div>
        </div>
    </div>
    <div id="exportImg"></div>

    <script>
        let endX
        let endY
        let flag = false
        let oldX = startX
        let oldY = startY
        const canvas = document.getElementById("canvas")
        const context = canvas.getContext("2d")
        const startX = canvas.getBoundingClientRect().left
        const startY = canvas.getBoundingClientRect().top
        context.fillStyle = "#000"
        context.lineWidth = 4
        context.strokeStyle = "white"
        context.fillRect(0, 0, canvas.width, canvas.height)
        canvas.addEventListener("mousedown", downEvent, false)
        canvas.addEventListener("mousemove", drawEvent, false)
        canvas.addEventListener("mouseup", upEvent, false)

        // 鼠标按下事件
        function downEvent(event) {
            flag = true
            oldX = event.clientX - startX
            oldY = event.clientY - startY
            context.beginPath()
        }
        // 鼠标移动事件
        function drawEvent() {
            if (flag) {
                endX = event.clientx - startX
                endY = event.clientY - startY
                context.moveTo(oldx, oldY)
                context.lineTo(endX, endY)
                context.stroke()
                oldX = endX
                oldY = endY
            }
        }


        // 鼠标移出画板
        function upEvent() {
            flag = false
            context.closePath()
        }

        // 清空画板内容
        function handleReset() {
            context.clearRect(0, 0, canvas.width, canvas.height)
            context.fillRect(0, 0, canvas.width, canvas.height)
        }

        // 保存 导出图片
        function handleSave() {
            canvas.toBlob(blob => {
                const date = Date.now().tostring()
                const link = document.createElement('a')
                link.download = `${date}.png`
                link.herf = URL.createObjectURL(blob)
                link.click()
                link.remove()
            })
        }
    </script>
</body>

</html>